import React, { useState } from "react";
import config from '../config/config';

export function useGlobalState() {

    const [collapsed, setCollapsed] = useState(false);
    const [mainMenuKey, setMainMenuKey] = useState(config.menu_main[0].key);
    const [sideMenuKey, setSideMenuKey] = useState(config.menu_side[mainMenuKey][0].key);

    const useDefalutMenuKey = (pathname) => {
        console.log("useGlobalState useDefalutMenuKey pathname => ", pathname);
        let mainKey = config.menu_main[0].key;
        let sideKey = config.menu_side[mainKey][0].key;
        const sideMenu = config.menu_side;
        const mainMenuKeys = Object.keys(sideMenu);
        for (let i = 0; i < mainMenuKeys.length; i++) {
            const tempKey = mainMenuKeys[i];
            const sideMenuChilds = sideMenu[tempKey];
            for (let j = 0; j < sideMenuChilds.length; j++) {
                let sideMenuChildren = sideMenuChilds[j];
                if (pathname.indexOf(sideMenuChildren.key) > -1) {
                    mainKey = tempKey;
                    sideKey = sideMenuChildren.key;
                }

                let sideSubMenuChilds = sideMenuChildren.children;
                if (sideSubMenuChilds) {
                    for (let k = 0; k < sideSubMenuChilds.length; k++) {
                        if (pathname.indexOf(sideSubMenuChilds[k].key) > -1) {
                            mainKey = tempKey;
                            sideKey = sideSubMenuChilds[k].key;
                        }
                    }
                }
            }
        }
        setMainMenuKey(mainKey);
        setSideMenuKey(sideKey);
        console.log("useGlobalState useDefalutMenuKey mainMenuKey => " + mainKey + " sideMenuKey => " + sideKey);
    }

    return {
        collapsed, setCollapsed,
        mainMenuKey, setMainMenuKey,
        sideMenuKey, setSideMenuKey,
        useDefalutMenuKey,
    };
}
